/*

Copyright (C) 2007 Thomas Geiger (tom.geiger@gmail.com)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

#include <octave/oct.h>

#include <sstream>
#include <string>

#include "globuscpp/URL.h"
#include "globuscpp/CredManager.h"
#include "globuscpp/GramJobCallback.h"

using namespace std;
using namespace globus_common;
using namespace globus_job;

static void usage() {
	error("gt_jobping('http://hostname')");
}

DEFUN_DLD(gt_jobping, 
          args, 
          , 
          "Check if the jobmanager is reachable."
          ) 
{	
	int argNum;
	string host;
	string jobHandle;
	bool success = false;
	
	// arg(0) => url
	argNum = args.length();
	
	if (argNum < 1)  {
		error("Invalid arguments");	
		usage();
		return octave_value(false);
	}

	// parse args
	host = args(0).string_value();
	
	if(host.empty()) {
		usage();
		return octave_value(false);
	}
	
	// check for existing certificate or aquire one
	CredManager credMgr;	                                            
	if ( !credMgr.hasCredential() ) {
		cerr << "You are not authorized within the grid." << endl;
		return octave_value(false);
	}
	
	URL* url = URL::Create(host);
	if (url != NULL) {	
		GramJobCallback callbackServer;
    	GramJob job = GramJob(&callbackServer);
    	success = job.ping(url);
    	if (!success) {
    		cerr << "Could not reach host: "<< url->getHost() << "."<< endl;
    	}
	}
    
    return octave_value(success);
}
